package com.platform.framework.web.service.web;

import com.alibaba.fastjson2.JSONObject;
import com.platform.common.core.domain.entity.WebUser;
import com.platform.common.core.domain.model.WebLoginUser;
import com.platform.common.enums.ResultEnum;
import com.platform.common.exception.BusinessException;
import com.platform.common.utils.StringUtils;
import com.platform.system.domain.dto.device.HumanModelManagerDto;
import com.platform.system.domain.dto.device.WebUserInfoDto;
import com.platform.system.domain.vo.device.WebUserInfoVo;
import com.platform.system.service.ISysHumanModelManagerService;
import com.platform.system.service.ISysWebUserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author Huangkai
 */
@Slf4j
@Service("loginByPhoneService")
public class UsernamePhoneUserDetailsServiceImpl implements UserDetailsService {

    @Resource
    ISysWebUserInfoService sysWebUserInfoService;

    @Override
    public UserDetails loadUserByUsername(String loginUserInfo) throws UsernameNotFoundException {
        JSONObject jsonObject = JSONObject.parse(loginUserInfo);
        log.info("传过来的信息 {}", jsonObject);
        WebUserInfoVo webUserInfoVo = new WebUserInfoVo();
        String phone = jsonObject.getString("phone");
        webUserInfoVo.setPhone(phone);
        if(jsonObject.containsKey("openId")) {
            String openId = jsonObject.getString("openId");
            webUserInfoVo.setOpenId(openId);
        }

        WebUserInfoDto webUserInfoDto = sysWebUserInfoService.selectWebUser(webUserInfoVo);
        log.info("查询信息{}", webUserInfoDto);
        if(webUserInfoDto == null){
            // 新增用户信息
            Boolean flag = sysWebUserInfoService.insertWebUser(webUserInfoVo);
            log.info("插入用户信息{}", flag);
            if(!flag){
                throw new BusinessException(ResultEnum.LOGIN_FAIL);
            }
            webUserInfoDto = sysWebUserInfoService.selectWebUser(webUserInfoVo);
        }
        log.info("查询的用户信息{}", webUserInfoDto);
        return createWebLoginUser(webUserInfoDto);
    }

    /**
     * 创建登陆用户
     * @param webUserInfoDto
     * @return
     */
    public UserDetails createWebLoginUser(WebUserInfoDto webUserInfoDto) {
        WebUser webUser = new WebUser();
        webUser.setUid(webUserInfoDto.getUid());
        webUser.setNick(webUserInfoDto.getNick());
        webUser.setPhone(webUserInfoDto.getPhone());
        webUser.setLoginDate(new Date());
        webUser.setOpenId(webUserInfoDto.getOpenId());
        return new WebLoginUser(webUserInfoDto.getUid(),  webUser);
    }
}